<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/6/20
 * Time: 15:28
 */

namespace app\index\model;


use think\Model;

class CrmCustomerCode extends Model
{

    public function code($input){
        if (!empty($input['starttime']) && !empty($input['endtime'])) {
            if($input['starttime']>$input['endtime'])apiReturn(400,'查询开始日期不能大于结束日期');//username m.username,m.name as manage_name
            $where['c.receive_time']=['between',[strtotime($input['starttime']),strtotime($input['endtime'])]];
        }
        if(!empty($input['phone'])){
            $where['c.phone']=$input['phone'];
        }
        if(!empty($input['name'])){
            $where['customer.name']=['LIKE',"%".$input['name']."%"];
        }
        if(isset($where)){
            $res = $this->alias('c')->join('crm_customer customer','c.client_id=customer.client_id','left')->where($where)->field('c.code,c.status,c.phone,c.receive_time,customer.manage_id,customer.name')->order('c.status desc c.receive_time desc')->limit($input['limit'])->page($input['page'])->select();
            $count = $this->alias('c')->join('crm_customer customer','c.client_id=customer.client_id','left')->where($where)->count();
        }else{
            $res = $this->alias('c')->join('crm_customer customer','c.client_id=customer.client_id','left')->field('c.code,c.status,c.phone,c.receive_time,customer.manage_id,customer.name')->order('c.status desc c.receive_time desc')->limit($input['limit'])->page($input['page'])->select();
            $count = $this->alias('c')->join('crm_customer customer','c.client_id=customer.client_id','left')->count();
        }
        $crm_manageM =new  CrmManage();
        foreach ($res as &$value){
            $value['username']='';
            $value['manage_name']='';
            if(!empty($value['manage_id'])){
                $manage = $crm_manageM->where('username',$value['manage_id'])->find();
                $value['username']=$manage['username'];
                $value['manage_name']=$manage['name'];
            }
        }
        return ['list'=>$res,'count'=>$count];
    }
}